package com.jyy.prefabricated.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jyy.prefabricated.common.AjaxResult;
import com.jyy.prefabricated.dto.BatchDto;
import com.jyy.prefabricated.dto.Pageable;
import com.jyy.prefabricated.entity.MessageInfo;
import com.jyy.prefabricated.entity.SysUser;
import com.jyy.prefabricated.service.MessageInfoService;
import com.jyy.prefabricated.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 消息通知
 * @version 1.0.0
 * @author: zjj
 */
@Slf4j
@RequestMapping("/api")
@RestController
public class MessageInfoController {

    @Autowired
    private MessageInfoService messageInfoService;

    @Autowired
    private UserUtils userUtils;

    /**
     * 批量修改消息状态
     * @param dto
     * @return
     */
    @PutMapping("/message-batch")
    public AjaxResult update(@Valid @RequestBody BatchDto dto){
        log.info("Rest request to batch-update message:{}",dto);
        messageInfoService.batchUpdateStatus(dto);
        return AjaxResult.success();
    }

    /**
     * 批量删除消息
     * @param dto
     * @return
     */
    @DeleteMapping("/message-batch")
    public AjaxResult deleteById(@RequestBody BatchDto dto){
        log.info("Rest request to batch-delete message by id:{}",dto);
        int row = messageInfoService.batchDelete(dto);
        if(row > 0){
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }


    /**
     * 删除消息
     * @param id
     * @return
     */
    @DeleteMapping("/message/{id}")
    public AjaxResult deleteById(@PathVariable Integer id){
        log.info("Rest request to delete message by id:{}",id);
        int row = messageInfoService.delete(id);
        if(row > 0){
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 获取当前用户消息通知列表
     * @param pageable
     * @return
     */
    @GetMapping("/message")
    public AjaxResult selectByParams(Pageable pageable){
        SysUser user = userUtils.getCurrentUser();
        log.info("Rest request to find message by userId:{}", user.getId());
        PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<MessageInfo> messageInfos = messageInfoService.selectByParams(user.getId());
        PageInfo<MessageInfo> result = new PageInfo<>(messageInfos);
        return AjaxResult.success(result);
    }
}
